<template>
  <div class="h-[375px] w-[375px]">
    <vue-cropper
      ref="cropper"
      v-bind="state.option"
      @imgLoad="imgLoad"
      @imgLoadError="imgLoad"
    ></vue-cropper>
  </div>
</template>
<script lang="ts" setup>
import { blobToFile } from "@/utils/common";

interface State {
  option: any;
  loading: boolean;
}
const props = defineProps({
  img: {
    type: String,
    default: ""
  },
  imgName: {
    type: String,
    default: ""
  }
});
const emit = defineEmits(["close", "success"]);
const cropper = ref();
const state = reactive<State>({
  option: {
    img: props.img,
    size: 1,
    full: true,
    zoomable: true,
    zoomableTouch: true,
    outputType: "jpeg",
    mode: "contain",
    original: false,
    canMove: true,
    canMoveBox: true,
    autoCrop: true,
    fixed: true,
    centerBox: true,
    canScale: true,
    fixedNumber: [1, 1],
    outputSize: 0.5,
    high: false
  },
  loading: false
});
const imgLoad = (msg: any) => {
  console.log(msg);
};
const getAvatar = async () => {
  return new Promise(resolve => {
    cropper.value.getCropBlob(async (data: any) => {
      const name = props.imgName.substring(0, props.imgName.lastIndexOf("."));
      const file = await blobToFile(data, `${name}.png`);
      resolve(file);
    });
  });
};
watch(
  () => props.img,
  val => {
    state.option.img = val;
  }
);
defineExpose({
  getAvatar
});
</script>
